<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\TourEnroll;
use app\common\model\TourRoute;
use app\common\model\TourTemplate;
use app\common\model\TourTourist;
use app\common\model\TourVisitor;
use ffhome\frame\controller\CrudController;
use think\db\BaseQuery;

class Enroll extends CrudController
{
    protected $modelName = TourEnroll::MODEL_NAME;
    protected $alias = 'e';

    public function index()
    {
        return $this->indexOperate();
    }

    protected function getSearchFields(): string
    {
        return "{$this->alias}.id,{$this->alias}.user_id,{$this->alias}.adult_num,{$this->alias}.child_num"
            . ",{$this->alias}.market_money,{$this->alias}.linkman,{$this->alias}.mobile,{$this->alias}.status"
            . ",{$this->alias}.single_price,{$this->alias}.market_rebate_money,{$this->alias}.create_time"
            . ",t.pic,t.name,r.start,t.days";
    }

    protected function getBaseModel(): BaseQuery
    {
        return parent::getBaseModel()
            ->leftJoin(TourRoute::MODEL_NAME . ' r', "{$this->alias}.route_id=r.id")
            ->leftJoin(TourTemplate::MODEL_NAME . ' t', "r.template_id=t.id");
    }

    protected function buildWhere(array $param): array
    {
        $where = parent::buildWhere($param);
        $where[] = ["{$this->alias}.user_id", '=', $this->getCurrentUserId()];
        return $where;
    }

    public function add()
    {
        $this->addOperate();
    }

    protected function getAddFilterFields(): array
    {
        return ['route_id', 'adult_num', 'child_num', 'single_price', 'linkman', 'mobile', 'email'];
    }

    protected function onBeforeAdd(array &$data)
    {
        $data['status'] = TourEnroll::S_UNCONFIRMED;
        $data['user_id'] = $this->getCurrentUserId();
        TourEnroll::computeMoney($data);
        parent::onBeforeAdd($data);
    }

    protected function onAfterAdd(array &$data)
    {
        $visitorIds = explode(',', request()->param('visitor_ids', ''));
        $list = TourVisitor::getTouristListByIds($visitorIds);
        foreach ($list as $tourist) {
            $tourist['enroll_id'] = $data['id'];
            TourTourist::add($tourist);
        }
        parent::onAfterAdd($data);
    }

    public function detail(int $id)
    {
        $row = $this->getModelInfo($id);
        if ($row['user_id'] !== $this->getCurrentUserId()) {
            $this->error(lang('enroll.only_operate_owner_order'));
        }
        TourRoute::convert($row);
        convertNumber($row);
        $row['tourists'] = TourTourist::getListByEnrollId($row['id']);
        $this->json_result($row);
    }

    protected function getCurrentUserId()
    {
        return currentMember()['id'];
    }

    protected function onBeforeDelete($id): array
    {
        $this->error(lang('enroll.nonsupport_delete_operate'));
    }
}